Find All Duplicates in an Array
Question
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
|
|
Analysis
从头遍历数组,数字num对应index的数字变为负数,假如遍历到某数num为负,代表该index出现过一次,将index+1添加到res中
Code
|
|
Find All Numbers Disappeared in an Array
Question
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
|
|
Analysis
同上,将出现过的num对应index的数字变为负的,第二次遍历的时候假如某数num为正,代表该index数字未出现过
Code
|
|